import React, { useEffect } from 'react';
import { Outlet, useLocation, useNavigate } from 'react-router-dom';
import { useAuth } from '../hooks/useAuth';
import { 
  List,
  ListItemIcon,
  ListItemText,
  CssBaseline,
} from '@mui/material';
import DashboardIcon from '@mui/icons-material/Dashboard';
import EventIcon from '@mui/icons-material/Event';
import LogoutIcon from '@mui/icons-material/Logout';
import {
  StyledDrawer,
  LogoContainer,
  AppTitle,
  AppSubtitle,
  NavigationContainer,
  NavItem,
  NavButton,
  LogoutContainer,
  MainContent,
  PageContent,
} from './RootLayout.styles';

const menuItems = [
  { text: 'Dashboard', icon: <DashboardIcon />, path: '/dashboard' },
  { text: 'Meetings', icon: <EventIcon />, path: '/meetings' },
];

const RootLayout: React.FC = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const { user, isInit, logout } = useAuth();

  useEffect(() => {
    if (isInit && user && location.pathname === '/') {
      navigate("/dashboard");
    }
  }, [isInit, user, location.pathname, navigate]);

  const handleLogout = () => {
    logout();
    navigate('/login');
  };

  return (
    <MainContent>
      <CssBaseline />
      <StyledDrawer variant="permanent">
        <LogoContainer>
          <AppTitle variant="h4">
            <EventIcon sx={{ fontSize: 40 }} />
            MM
          </AppTitle>
          <AppSubtitle variant="subtitle2">
            Meeting Management
          </AppSubtitle>
        </LogoContainer>
        <NavigationContainer>
          <List>
            {menuItems.map((item) => (
              <NavItem key={item.text} to={item.path}>
                <NavButton selected={location.pathname === item.path}>
                  <ListItemIcon>
                    {item.icon}
                  </ListItemIcon>
                  <ListItemText primary={item.text} />
                </NavButton>
              </NavItem>
            ))}
          </List>
        </NavigationContainer>
        <LogoutContainer>
          <NavButton onClick={handleLogout}>
            <ListItemIcon>
              <LogoutIcon />
            </ListItemIcon>
            <ListItemText primary="Logout" />
          </NavButton>
        </LogoutContainer>
      </StyledDrawer>
      <PageContent>
        <Outlet />
      </PageContent>
    </MainContent>
  );
};

export default RootLayout;
